<?php
session_start();
if(isset($_SESSION['user']))
	header('location: index.php');

?>
<html>
<head>
<title>ShareCon - Registration</title>
</head>
<body>

<div id="main" style="padding-left:15%; padding-right:15%">
<div id="inner" style="border: 2px solid black; padding:5%;">

<?php
//check that there is a post array with values
if (count($_POST) == 5) {
	if (strlen($_POST['pid']) > 0 &&
	strlen($_POST['password']) > 0 &&
	strlen($_POST['password2']) > 0  &&
	strlen($_POST['fname']) > 0  &&
	strlen($_POST['lname']) > 0 ) {
		$pid = htmlspecialchars(trim($_POST['pid']));
		$pwd = md5(htmlspecialchars($_POST['password']));
		$pwd2 = md5(htmlspecialchars($_POST['password2']));
		$fname = htmlspecialchars(trim($_POST['fname']));
		$lname = htmlspecialchars(trim($_POST['lname']));

		$con = mysqli_connect("localhost", "root", NULL, "csproj2");
		if (mysqli_connect_errno()) {
			printf("Connect failed: %s", mysqli_connect_error());
			exit();
		}

		$stmt = $con->prepare("SELECT count(p_id) FROM person WHERE p_id = ?");
		$stmt->bind_param('s', $pid);
		$stmt->execute();
		$stmt->bind_result($pid_count);
		$stmt->fetch();
		$stmt->close();

		if ($pid_count == 0) {
			if ($pwd == $pwd2) {
				$stmt = $con->prepare("INSERT INTO person VALUES (?, ?, ?, ?)");
				$stmt->bind_param('ssss', $pid, $pwd, $fname, $lname);
				$stmt->execute();
				$stmt->close();

				session_start();
				$_SESSION['user'] = $pid;
				header('location: index.php');		

			} else {
				printf("<span style='color:red'>Passwords do not match!</span>");
			}
		} else {
			printf("<span style='color:red'>Username already taken!</span>");
		}
	
	} else {
		printf("<span style='color:red'>Not all fields have been filled!</span>");
	}

}
?>

<div id='loginset'>
<br>
<h1>Login</h1>

<form id='loginforms' method="post" action="register.php">
<table border='0'>
<tr>
	<td>Username:</td>
	<td><input type="text" name="pid" /></td>
</tr>
<tr>
	<td>Password:</td>
	<td><input type="password" name="password" /></td>
</tr>
<tr>
	<td>Re-enter Password:</td>
	<td><input type="password" name="password2" /></td>
</tr>
<tr>
	<td>First Name:</td>
	<td><input type="text" name="fname" /></td>
</tr>
<tr>
	<td>Last Name:</td>
	<td><input type="text" name="lname" /></td>
</tr>
<tr>
	<td></td>
	<td><input type="submit" value="Create User" style='float:right' /></td>
</tr>
</table>
</form>

<span>Already have an account? <a href="/login.php">Login here!</a></span><br>
<span>Return to the <a href="/index.php">home page.</a></span>


</div>
</div></div>
</body>
</html>
